package com.kcnet.qk.service;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.kcnet.qk.MyApplication;
import com.kcnet.qk.app.App;
import com.kcnet.qk.app.AppContext;
import com.kcnet.qk.constant.Const;
import com.kcnet.qk.controller.MyWindowManager;
import com.kcnet.qk.model.MessageEvent;
import com.kcnet.qk.netty.NettyClient;
import com.kcnet.qk.netty.NettyListener;
import com.kcnet.qk.util.AppUtil;
import com.kcnet.qk.util.JsonNettyData;
import com.kcnet.qk.util.PreferenceHelper;
import com.kcnet.qk.util.ToastUtil;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import cn.jesse.nativelogger.NLogger;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import retrofit2.http.HTTP;

/**
 * Created by LiuSaibao on 11/17/2016.
 */
public class CoreService extends Service implements NettyListener,Runnable {


    private static final String TAG = "CoreService";
    private ScheduledExecutorService mScheduledExecutorService;
    private Dialog Dialog;
    private Timer timer;

    private Thread thread;


    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        //checkUpdataApp();
        showFlowWindow();
        initSocket();
        //checkTime();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            if(intent.getIntExtra("id",-1) == 1){
                connect();
            }
        }catch (Exception e){

        }

        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 默认启动服务后就打开我们的拖动的小精灵
     */
    private void showFlowWindow() {
        if (!MyWindowManager.isWindowShowing()) {
            MyWindowManager.createSmallWindow(getApplicationContext());
        }


    }





    /**
     * 初始化Socket长连接服务 维护和PC软件交互
     */
    private void initSocket() {

        String ip = AppUtil.loadIPConf();
        NLogger.d(TAG,"读取共享目录的服务端IP地址:"+ip);
        if(TextUtils.isEmpty(ip)){
          //  showInputIP();
        }else {
            PreferenceHelper.putString(Const.HOST, ip);
            NettyClient.getInstance().setListener(this);
            connect();
        }
        sendHeatboot();
    }

    public void sendHeatboot(){

        //发送登录数据包
        TelephonyManager tm = (TelephonyManager) this
                .getSystemService(Context.TELEPHONY_SERVICE);//
        String deviceId = tm.getDeviceId();
        final String body = "{\"code\":200,\"imei\":\"" + deviceId + "\"}";


       // NLogger.i("HTML", "发送登录数据:" + body);

        // 自定义心跳，每隔20秒向服务器发送心跳包
        mScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        mScheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

                NettyClient.getInstance().senHartBoot(body.getBytes());

            }
        }, 1, 30, TimeUnit.SECONDS);
    }

    /**
     * 检测更新APP升级
     */
    private void checkUpdataApp() {
        Log.d("HTML","checkUpdataApp:");
        AjaxParams ps = new AjaxParams();
        final  int version = AppUtil.getVersionCode(this);
        ps.put("version",""+AppUtil.getVersionCode(this));
        MyApplication.http.get("http://wxapi.likangjun.com/api/index/appVersion", ps, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                super.onSuccess(s);
                NLogger.d("HTML","onSuccess:"+s);
                try {
                    JSONObject jb = new JSONObject(s);
                    if(jb.getInt("code") == 1){
                        int jbversion =  jb.getJSONObject("data").getInt("version");
                       String url =  jb.getJSONObject("data").getString("url");
                        if(jbversion > version){
                            Intent intent  = new Intent(CoreService.this,UpdateService.class);
                            intent.putExtra("appname","FB精灵");
                            intent.putExtra("appurl",url);
                            startService(intent);
                        }
                    }else {

                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                NLogger.d("HTML","onFailure:"+strMsg);
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent data) {
        Log.i(TAG, "changeController");
        //tcp状态检测
        if (data.getCode() == 1) {
            ToastUtil.showToast(getBaseContext(), "连接状态:" + NettyClient.getInstance().getConnectStatus());
        } else if (data.getCode() == 100) {
         //   showInputIP();
        }
    }

    public void checkTime() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //do something
                if(AppContext.taskId != -1){
                   int xTime = (int) ((System.currentTimeMillis() - AppContext.taskStartTime)/1000/60);
                    Log.i(TAG, "xTime:"+xTime);
                   if(xTime >= 30){
                     //  ToastUtil.showToast(CoreService.this,"任务执行超过5分钟了直接停止任务");
                       NLogger.i(TAG, "任务执行超过30分钟了直接停止任务 taskId:"+AppContext.taskId+" taskType:"+AppContext.taskType);
                       stopTask();
                   }
                }
            }
        }, 1000,10000);//延时1s执行


    }

    public void stopTask() {
        JsonNettyData.sendToServerFlag(AppContext.taskId,3,"任务执行超时");
        AppContext.taskId = -1;
        PreferenceHelper.putBoolean(Const.PREF_KEY_STOP_AUTO_FLAG, false);
        EventBus.getDefault().post(new Boolean(false));
        try {
            ToastUtil.showToast(AppContext.getInstance().getContext(), "任務執行完畢 停止任務");
        }catch (Exception e){

        }
       // NLogger.i(TAG, "停止任务 ");
    }


//    public void showInputIP() {
//        // AlertDialog dialog = alertDialog.create();
//        if (Dialog == null) {
//            AlertDialog.Builder builder = new AlertDialog.Builder(this);
//
//            builder.setTitle("请输入IP");
//            final EditText editText = new EditText(this);
//            editText.setHint("请输入IP地址");
//            editText.setText(PreferenceHelper.getString(Const.HOST, ""));
//            builder.setView(editText);
//            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//
//                    String ip = editText.getText().toString();
//                    if (TextUtils.isEmpty(ip)) {
//                        Toast.makeText(getBaseContext(), "不允许输入为空", Toast.LENGTH_SHORT).show();
//                    }
//                    PreferenceHelper.putString(Const.HOST, ip);
//                    dialog.dismiss();
//                    connect();
//                }
//            });
//            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
//                }
//            });
//            Dialog = builder.create();
//            Dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//        }
//        if (!Dialog.isShowing()) {
//            Dialog.show();
//        }
//    }

    @Override
    public void onServiceStatusConnectChanged(int statusCode) {        //连接状态监听
        NLogger.d(TAG, "connect status:" + statusCode);
        if (statusCode == NettyListener.STATUS_CONNECT_SUCCESS) {

            Log.d(TAG, " 连接服务器成功");
            authenticData();
        } else if (statusCode == NettyListener.STATUS_CONNECT_ERROR) {
            EventBus.getDefault().post(new MessageEvent(100));
            //   connect();
           // showInputIP();
            Log.d(TAG, "tcp connect error");
            //ettyClient.getInstance().reconnect();
            //  WriteLogUtil.writeLogByThread("tcp connect error");
        }
    }


    @Override
    public void onMessageResponse(ByteBuf byteBuf) {

        byte[] req = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(req);

        String body = null;
        try {
            body = new String(req, "UTF-8");
            NLogger.d(TAG, "客户端收到消息  :" + body);
            JsonNettyData.pasrsJson(body);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


    }

    @SuppressLint("MissingPermission")
    private void authenticData() {
        //发送登录数据包
        TelephonyManager tm = (TelephonyManager) this
                .getSystemService(Context.TELEPHONY_SERVICE);//
        String deviceId = tm.getDeviceId();
        String body = "{\"code\":1,\"imei\":\"" + deviceId + "\"}";
        NLogger.i("HTML", "发送登录数据:" + body);
        NettyClient.getInstance().sendMsgToServer(body.getBytes());
        return;

    }


    private void handle(int t, int i, int f) {
        // TODO 实现自己的业务逻辑
    }

    private void connect() {
        if(thread != null){
            thread.interrupt();
        }
        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        shutdown();
        NettyClient.getInstance().setReconnectNum(0);
        NettyClient.getInstance().disconnect();
    }

    private void shutdown() {
        if (mScheduledExecutorService != null) {
            mScheduledExecutorService.shutdown();
            mScheduledExecutorService = null;
        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public void run() {
        NettyClient.getInstance().connect();//连接服务器
    }
}
